const app = getApp()
const i18n = require('../../i18n/index')
Page({
  data: {
    tempCanvasWidth:0,
    tempCanvasHeight:0,
    imgViewHeight:0,
    page:'mainPage',
    imageNotChoosed:true,
    minScale: 0.5,
    maxScale: 2.5,
    doodleImageSrc:'',
    tempImageSrc:'',
    originImageSrc:'',
    imgWidth:0,
    imgHeight:0,
    imgTop:0,
    imgLeft:0,
    isCroper:false,
    // 多语言文本
    l10n: {},
    // 裁剪框 宽高
    cutW: 0,
    cutH: 0,
    cutL: 0,
    cutT: 0,
    //涂鸦窗口
    canvasHeight: 0,   //canvas动态高度，单位rpx
    isChooseColor:false,
    isChooseQuickBrush:false,
    // isChooseBack:false,
    isEraser:false,
    allColor: ['#000000', '#7f7f7f', '#880015', '#ed1c24', '#ff7f27', '#fff200', '#22b14c', '#00a2e8','#ffaec9','#a349a4','#ffffff','#c3c3c3'],
    //添加文字
    isChooseFontSize: false,
    isChooseFontColor: false,
    isChooseFontPattern: false,
    allText:{},
    // texted:false,
    inputFocus:false,
    
    // 贴图相关
    stickers: [], // 贴图数组
    activeStickerId: null, // 当前选中的贴图ID
    stickerIdCounter: 0, // 贴图ID计数器
    isChooseEmoji: false, // 是否显示emoji选择器
    isChooseCustomImage: false, // 是否显示自定义图片选择器
    emojiList: [
      '😀', '😃', '😄', '😁', '😆', '😅', '😂', '🤣', '😊', '😇', 
      '🙂', '🙃', '😉', '😌', '😍', '🥰', '😘', '😗', '😙', '😚',
      '😋', '😛', '😝', '😜', '🤪', '🤨', '🧐', '🤓', '😎', '🤩',
      '🥳', '😏', '😒', '😞', '😔', '😟', '😕', '🙁', '☹️', '😣',
      '😖', '😫', '😩', '🥺', '😢', '😭', '😤', '😠', '😡', '🤬',
      '🤯', '😳', '🥵', '🥶', '😱', '😨', '😰', '😥', '😓', '🤗',
      '🤔', '🤭', '🤫', '🤥', '😶', '😐', '😑', '😬', '🙄', '😯',
      '😦', '😧', '😮', '😲', '🥱', '😴', '🤤', '😪', '😵', '🤐'
    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var self = this
    console.log('modifyPhoto 页面加载，参数:', options)
    
    // self.device = wx.getSystemInfoSync()
    self.device = app.globalData.myDevice
    self.deviceRatio = self.device.windowWidth / 750
    // 调整图片视图高度，为顶部导航栏和底部工具栏留出空间
    self.imgViewHeight = self.device.windowHeight - 320 * self.deviceRatio
    // 初始化字体大小默认值
    self.fontSize = 18
    // 初始化画笔宽度默认值
    self.lineWidth = 5
    self.setData({
      imgViewHeight: self.imgViewHeight,
      page: 'mainPage'
    })
    // 初始化多语言文本
    this.updateTexts()
    
    // 检查是否来自表盘设置
    if (options.fromDial === 'true') {
      self.setData({
        fromDial: true,
        devScreenWidth: parseInt(options.width) || 240,
        devScreenHeight: parseInt(options.height) || 280,
        dialImagePath: decodeURIComponent(options.imagePath || ''),
      })
      // 直接加载传入的图片
      if (options.imagePath) {
        self.setData({
          imageNotChoosed: false,
          tempImageSrc: decodeURIComponent(options.imagePath),
          originImageSrc: decodeURIComponent(options.imagePath),
        })
        // 延迟加载，确保页面完全初始化
        setTimeout(function() {
          loadImgOnImage(self)
        }, 100)
      }
    } else {
      // 普通模式
      self.setData({
        fromDial: false,
      })
      chooseImage(self)
    }
  },

  onShow: function () {
    this.updateTexts()
  },

  // 多语言：更新界面文案
  updateTexts: function() {
    const l10n = buildL10n()
    try { wx.setNavigationBarTitle({ title: l10n.title }) } catch (e) {}
    this.setData({ l10n })
  },

  chooseOneImage(){
    chooseImage(this)
  },
  toMainPage(){
    loadImgOnImage(this)
    this.setData({
      page:'mainPage'
    })
  },
  toCropPage(){
    var self=this
    autoSaveStickerIfNeeded(self, function() {
      loadImgOnImage(self)
      self.setData({
        page: 'cropPage',
        allText:{}
      })
    })
  },
  bestShow(){
    loadImgOnImage(this)
  },
  uploadScaleStart(e) { //缩放图片
    let self = this
    let xDistance, yDistance
    let [touch0, touch1] = e.touches
    //self.touchNum = 0 //初始化，用于控制旋转结束时，旋转动作只执行一次

    //计算第一个触摸点的位置，并参照该点进行缩放
    self.touchX = touch0.clientX
    self.touchY = touch0.clientY
    //每次触摸开始时图片左上角坐标
    self.imgLeft = self.startX
    self.imgTop = self.startY

    // 两指手势触发
    if (e.touches.length >= 2) {
      self.initLeft = (self.deviceRatio * 750 / 2 - self.imgLeft) / self.oldScale
      self.initTop = (self.imgViewHeight / 2 - self.imgTop) / self.oldScale
      //计算两指距离
      xDistance = touch1.clientX - touch0.clientX
      yDistance = touch1.clientY - touch0.clientY
      self.oldDistance = Math.sqrt(xDistance * xDistance + yDistance * yDistance)
    }
  },

  uploadScaleMove(e) {
    fn(this, e)
  },

  uploadScaleEnd(e) {
    let self = this
    self.oldScale = self.newScale || self.oldScale
    self.startX = self.imgLeft || self.startX
    self.startY = self.imgTop || self.startY
  },
  croperStart(e){
    this.croperX = e.touches[0].clientX
    this.croperY = e.touches[0].clientY
  },
  croperMove(e){
    var self = this
    var dragLengthX = (e.touches[0].clientX-self.croperX)
    var dragLengthY = (e.touches[0].clientY-self.croperY)
    var minCutL = Math.max(0,self.data.imgLeft)
    var minCutT = Math.max(0, self.data.imgTop)
    var maxCutL = Math.min(750 * self.deviceRatio - self.data.cutW, self.data.imgLeft + self.data.imgWidth - self.data.cutW)
    var maxCutT = Math.min(self.imgViewHeight - self.data.cutH, self.data.imgTop + self.data.imgHeight - self.data.cutH)
    var newCutL = self.data.cutL + dragLengthX
    var newCutT = self.data.cutT + dragLengthY
    if (newCutL < minCutL) newCutL = minCutL
    if (newCutL > maxCutL) newCutL = maxCutL
    if (newCutT < minCutT) newCutT = minCutT
    if (newCutT > maxCutT) newCutT = maxCutT
    this.setData({
      cutL: newCutL,
      cutT: newCutT,
    })
    self.croperX = e.touches[0].clientX
    self.croperY = e.touches[0].clientY
  },
  dragPointStart(e){
    var self = this
    self.dragStartX = e.touches[0].clientX
    self.dragStartY = e.touches[0].clientY
    self.initDragCutW = self.data.cutW
    self.initDragCutH = self.data.cutH
  },
  dragPointMove(e){
    var self = this
    var maxDragX = Math.min(750 * self.deviceRatio, self.data.imgLeft + self.data.imgWidth)
    var maxDragY = Math.min(self.imgViewHeight, self.data.imgTop + self.data.imgHeight)
    var dragMoveX = Math.min(e.touches[0].clientX , maxDragX),
      dragMoveY = Math.min(e.touches[0].clientY, maxDragY);
    var dragLengthX = dragMoveX - self.dragStartX
    var dragLengthY = dragMoveY - self.dragStartY
    if (dragLengthX + self.initDragCutW >= 0 && dragLengthY + self.initDragCutH>=0){
      self.setData({
        cutW: self.initDragCutW + dragLengthX,
        cutH: self.initDragCutH + dragLengthY
      })
    } else {
      return
    }
  },
  openCroper(){
    var minCutL = Math.max(0, this.data.imgLeft)
    var minCutT = Math.max(0, this.data.imgTop)
    this.setData({
      isCroper:true,
      cutW: 205,
      cutH: 155,
      cutL: minCutL,
      cutT: minCutT
    })
  },
  competeCrop(){
    var self=this
    wx.showLoading({
      title: i18n.t('modify.cropping'),
      mask: true,
    })
    //图片截取大小
    var sX = (self.data.cutL - self.data.imgLeft) * self.initRatio / self.oldScale
    var sY = (self.data.cutT - self.data.imgTop) * self.initRatio / self.oldScale
    var sW = self.data.cutW * self.initRatio /self.oldScale
    var sH = self.data.cutH * self.initRatio / self.oldScale
    self.setData({
      isCroper: false,
      tempCanvasWidth: sW,
      tempCanvasHeight: sH
    })

    //真机疑似bug解决方法
    if (sW < self.scaleWidth * self.initRatio/ self.oldScale / 2) {
      sW *= 2
      sH *= 2
    }
    var ctx = wx.createCanvasContext('tempCanvas')
    ctx.drawImage(self.data.tempImageSrc, sX, sY, sW, sH, 0, 0, sW, sH)
    ctx.draw()
    //保存图片到临时路径
    saveImgUseTempCanvas(self, 100, loadImgOnImage)
  },
  cancelCrop(){
    this.setData({
      isCroper: false
    })
  },
//涂鸦窗口
  toDoodlePage(){
    var self = this
    autoSaveStickerIfNeeded(self, function() {
      loadImgOnCanvas(self)

      // 使用固定的画布高度，确保画布位置稳定
      var fixedCanvasHeight = self.device.windowHeight - 320 * self.deviceRatio
      self.setData({
        page:'doodlePage',
        canvasHeight: fixedCanvasHeight,
        allText: {},
        showBrushPreview: false,
        isChooseQuickBrush: false
      })
      // 确保imgViewHeight在整个涂鸦过程中保持稳定
      if (!self.imgViewHeight) {
        self.imgViewHeight = fixedCanvasHeight
      }
    })
  },
  doodleStart: function (e) {
    var self = this
    self.lineWidth = self.lineWidth ? self.lineWidth : 5
    self.lineColor = self.lineColor ? self.lineColor : '#000000'
    // 开始画图，隐藏所有的操作栏（不改变画布高度，避免画布移动）
    this.setData({
      isChooseColor: false,
      isChooseQuickBrush: false
      // isChooseBack: false,
      // 移除动态改变canvasHeight的代码，保持固定高度
    })
    self.doodleStartX = e.touches[0].x - 750 / 2 * self.deviceRatio
    self.doodleStartY = e.touches[0].y - self.imgViewHeight / 2
    // 记录是否移动过，用于判断是点击还是拖拽
    self.hasMoved = false
    
    // 显示画笔预览
    self.showBrushPreview(e.touches[0].x, e.touches[0].y)
  },

  doodleMove: function (e) {
    // 触摸移动，绘制中。。。
    var self=this
    self.doodled=true
    self.hasMoved = true
    
    if (self.data.isEraser) {
      self.ctx.clearRect(e.touches[0].x - 750 / 2 * self.deviceRatio, e.touches[0].y - self.imgViewHeight / 2,30,30)
      self.ctx.draw(true);
      self.cleared=true
    } else {
      var endX = e.touches[0].x - 750 / 2 * self.deviceRatio
      var endY = e.touches[0].y - self.imgViewHeight / 2
      
      self.ctx.setStrokeStyle(self.lineColor);
      self.ctx.setLineWidth(self.lineWidth);
      self.ctx.setLineCap('round');
      self.ctx.setLineJoin('round');
      self.ctx.moveTo(self.doodleStartX, self.doodleStartY);
      self.ctx.lineTo(endX, endY);
      self.ctx.stroke();
      self.ctx.draw(true);
      

    }
    self.doodleStartX = e.touches[0].x - 750 / 2 * self.deviceRatio
    self.doodleStartY = e.touches[0].y - self.imgViewHeight / 2
  },

  doodleEnd: function (e) {
    var self = this
    // 如果没有移动过，说明是点击，画一个点
    if (!self.hasMoved && !self.data.isEraser) {
      self.doodled = true
      self.ctx.setStrokeStyle(self.lineColor);
      self.ctx.setLineWidth(self.lineWidth);
      self.ctx.setLineCap('round');
      self.ctx.setLineJoin('round');
      // 画一个很小的圆点
      self.ctx.beginPath();
      self.ctx.arc(self.doodleStartX, self.doodleStartY, self.lineWidth / 2, 0, 2 * Math.PI);
      self.ctx.fill();
      self.ctx.draw(true);
      

    }
    
    // 隐藏画笔预览
    self.hideBrushPreview()
  },

  // 显示画笔预览
  showBrushPreview: function(x, y) {
    var self = this
    if (self.data.isEraser) return
    
    // 创建预览元素
    if (!self.brushPreview) {
      self.brushPreview = wx.createSelectorQuery().select('.brush-preview')
    }
    
    self.setData({
      showBrushPreview: true,
      brushPreviewX: x - self.lineWidth / 2,
      brushPreviewY: y - self.lineWidth / 2,
      brushPreviewSize: self.lineWidth,
      brushPreviewColor: self.lineColor
    })
  },

  // 隐藏画笔预览
  hideBrushPreview: function() {
    this.setData({
      showBrushPreview: false
    })
  },



  chooseLineColor(){
    this.setData({
      isChooseColor: true,
      isChooseQuickBrush: false,
      // isChooseBack: false,
      isEraser: false
      // 移除动态改变canvasHeight，保持固定高度
    })
  },
  lineColorChange(e){
    this.lineColor = e.target.dataset.selected
  },

  // 选择快速画笔
  chooseQuickBrush(){
    this.setData({
      isChooseColor: false,
      isChooseQuickBrush: true,
      isEraser: false
      // 移除动态改变canvasHeight，保持固定高度
    })
  },

  // 快速画笔预设
  quickBrushPreset: function(e) {
    var preset = e.currentTarget.dataset.preset
    switch(preset) {
      case 'thin':
        this.lineWidth = 2
        this.lineColor = '#000000'
        break
      case 'medium':
        this.lineWidth = 5
        this.lineColor = '#ff69b4'
        break
      case 'thick':
        this.lineWidth = 10
        this.lineColor = '#ff1493'
        break
      case 'marker':
        this.lineWidth = 15
        this.lineColor = '#ff69b4'
        break
    }
    
    // 隐藏选择面板
    this.setData({
      isChooseColor: false,
      isChooseQuickBrush: false
      // 移除动态改变canvasHeight，保持固定高度
    })
    
    wx.showToast({
      title: i18n.t('modify.brushSwitched'),
      icon: 'success',
      duration: 1000
    })
  },

  chooseEraser(){
    // this.isClear=false
    this.setData({
      isEraser: !this.data.isEraser,
      isChooseColor: false,
      isChooseQuickBrush: false,
    })
  },
  chooseClear(){
    this.ctx.clearRect(-750 * this.deviceRatio / 2, -this.imgViewHeight / 2, 750 * this.deviceRatio, this.imgViewHeight);
    this.ctx.draw(true);
    this.setData({
      isEraser: false,
      isChooseColor: false,
      isChooseQuickBrush: false,
    })
    this.cleared = true
  },
  doodleToMainPage(){
    if(this.doodled){
      this.doodled=false
      wx.showLoading({
        title: i18n.t('modify.savingDoodle'),
        mask: true,
      })
      saveDoodle(this, loadImgOnImage)
      this.setData({
        page: 'mainPage'
      })
    }else{
      loadImgOnImage(this)
    }
    this.setData({
      page: 'mainPage'
    })
  },
  //添加文字
  toTextPage(){
    var self = this
    autoSaveStickerIfNeeded(self, function() {
      loadImgOnImage(self)
      self.setData({
        page:'textPage'
      })
    })
  },
  focusInput(){
    this.setData({
      inputFocus: !this.data.inputFocus,
    })
  },
  inputText(e){
    var allText = this.data.allText
    allText.someText = e.detail.value
    if (allText.someText.length == 0) {
      allText.someText = i18n.t('modify.tapToInput')
      }
    this.setData({
      allText: allText
    })
  },
  textMoveStart(e){
    this.textX = e.touches[0].clientX
    this.textY = e.touches[0].clientY
  },
  textMove(e){
    var allText = this.data.allText
    var dragLengthX = (e.touches[0].clientX - this.textX)
    var dragLengthY = (e.touches[0].clientY - this.textY)
    var minTextL = 0
    var minTextT = 0
    var maxTextL = (750 - 100) * this.deviceRatio
    var maxTextT = this.imgViewHeight - 40 * this.deviceRatio
    var newTextL = allText.textL + dragLengthX
    var newTextT = allText.textT + dragLengthY
    if (newTextL < minTextL) newTextL = minTextL
    if (newTextL > maxTextL) newTextL = maxTextL
    if (newTextT < minTextT) newTextT = minTextT
    if (newTextT > maxTextT) newTextT = maxTextT

    allText.textL = newTextL
    allText.textT = newTextT
    this.setData({
      allText: allText,
      isChooseFontSize: false,
      isChooseFontColor: false,
      isChooseFontPattern: false
    })
    this.textX = e.touches[0].clientX
    this.textY = e.touches[0].clientY
  },
  chooseaddText(){
    var allText={}
    allText={
      idx: allText.length - 1,
      someText: i18n.t('modify.tapToInput'),
      fontColor: this.fontColor ? this.fontColor:'rgba(20,20,20,0.8)',
      fontSize: this.fontSize ? this.fontSize:18,
      fontStyle: 'normal',
      fontWeight: 'normal',
      textL: (750 - 200) * this.deviceRatio / 2,
      textT: this.imgViewHeight / 2 - this.scaleHeight / 2 + 20,
      isTextActive: true,
    }
    this.setData({
      allText: allText,
      isChooseFontSize: false,
      isChooseFontColor: false,
      isChooseFontPattern: false
    })
  },
  cancelAddText(){
    var allText = this.data.allText
    allText.isTextActive = false
    this.setData({
      allText: allText,
      inputFocus:false,
      isChooseFontSize: false,
      isChooseFontColor: false,
      isChooseFontPattern: false
    })
  },
  competeAddText(){
    var self=this
    var allText = this.data.allText
    if (allText.someText == i18n.t('modify.tapToInput') || allText.someText == ""){
      this.cancelAddText()
    }else{
      wx.showLoading({
        title: i18n.t('modify.savingText'),
        mask: true,
      })
      allText.isTextActive = false
      var initRatio = self.initRatio
      if (self.initRatio<1){ //解决问题：小图或者过度裁剪后的图添加文字时文字虚化
        initRatio=1
      }
      var tempCanvasWidth = self.scaleWidth * initRatio
      var tempCanvasHeight = self.scaleHeight * initRatio

      this.setData({
        allText: allText,
        inputFocus: false,
        isChooseFontSize: false,
        isChooseFontColor: false,
        isChooseFontPattern: false,
        tempCanvasWidth: tempCanvasWidth,
        tempCanvasHeight: tempCanvasHeight
      })

      var ctx = wx.createCanvasContext('tempCanvas')
      ctx.drawImage(self.data.tempImageSrc, 0, 0, tempCanvasWidth, tempCanvasHeight)
      ctx.setFillStyle(allText.fontColor)
      var canvasFontSize = Math.ceil(allText.fontSize * initRatio)
      ctx.font = allText.fontStyle + ' ' + allText.fontWeight + ' ' + canvasFontSize + 'px sans-serif'
      ctx.setTextAlign('left')
      ctx.setTextBaseline('top')
      ctx.fillText(allText.someText, (allText.textL - self.startX) * initRatio, (allText.textT - self.startY+5)* initRatio)
      ctx.draw()
      //保存图片到临时路径
      saveImgUseTempCanvas(self, 100, null)
    }
  },
  chooseFontsize(){
    this.setData({
      isChooseFontSize: !this.data.isChooseFontSize,
      isChooseFontColor: false,
      isChooseFontPattern: false
    })
  },
  fontsizeSliderChange(e) {
    // 左边是小字体(8px)，右边是大字体(50px)
    this.fontSize = e.detail.value
    var allText = this.data.allText
    if (allText && allText.isTextActive){
      allText.fontSize = this.fontSize
      this.setData({
        allText: allText
      })
    }
  },

  chooseFontColor() {
    this.setData({
      isChooseFontSize: false,
      isChooseFontColor: !this.data.isChooseFontColor,
      isChooseFontPattern: false
    })
  },
  fontColorChange(e) {
    this.fontColor = e.target.dataset.selected
    var allText = this.data.allText
    if (allText && allText.isTextActive) {
      allText.fontColor = this.fontColor
      this.setData({
        allText: allText
      })
    }
  },
  chooseFontPattern(){
    this.setData({
      isChooseFontSize: false,
      isChooseFontColor: false,
      isChooseFontPattern: !this.data.isChooseFontPattern
    })
  },
  fontStyleChange(e){
    this.fontStyle = e.detail.value ? 'oblique' : 'normal'
    var allText = this.data.allText
    if (allText && allText.isTextActive) {
      allText.fontStyle = this.fontStyle
      this.setData({
        allText: allText
      })
    }
  },
  fontWeightChange(e){
    this.fontWeight = e.detail.value ? 'bold' : 'normal'
    var allText = this.data.allText
    if (allText && allText.isTextActive) {
      allText.fontWeight = this.fontWeight
      this.setData({
        allText: allText
      })
    }
  },
  textToMainPage(){
    loadImgOnImage(this)
    this.setData({
      allText: [],
      page:'mainPage'
    })
  },

  // 贴图页面相关函数
  toStickerPage(){
    var self = this
    loadImgOnImage(self)
    self.setData({
      page: 'stickerPage',
      allText: {},
      isChooseEmoji: false,
      isChooseCustomImage: false
    })
  },

  stickerToMainPage(){
    var self = this
    if (self.data.stickers.length > 0) {
      // 如果有贴图，保存合成图片
      saveStickerImage(self, loadImgOnImage)
    } else {
      loadImgOnImage(self)
    }
    self.setData({
      page: 'mainPage'
    })
  },

  // 仅保存贴图（不返回主页面）
  saveStickerOnly(){
    var self = this
    if (self.data.stickers.length > 0) {
      // 保存贴图到当前图片
      saveStickerImageOnly(self)
    } else {
      wx.showToast({
        title: i18n.t('modify.noStickerToSave'),
        icon: 'none',
        duration: 2000
      })
    }
  },

  // 显示/隐藏emoji选择器
  chooseEmoji(){
    this.setData({
      isChooseEmoji: !this.data.isChooseEmoji,
      isChooseCustomImage: false
    })
  },

  // 显示/隐藏自定义图片选择器
  chooseCustomImageSelector(){
    this.setData({
      isChooseEmoji: false,
      isChooseCustomImage: !this.data.isChooseCustomImage
    })
  },

  // 添加emoji贴图
  addEmojiSticker(e){
    var emoji = e.currentTarget.dataset.emoji
    
    // 使用固定的逻辑像素大小，不依赖设备比例
    var sticker = {
      id: ++this.data.stickerIdCounter,
      type: 'emoji',
      emoji: emoji,
      x: 100,
      y: 100,
      width: 80,
      height: 80,
      fontSize: 60,
      zIndex: this.data.stickerIdCounter,
      isActive: false,
      scale: 1,
      rotation: 0
    }
    
    var stickers = this.data.stickers
    stickers.push(sticker)
    
    this.setData({
      stickers: stickers,
      stickerIdCounter: this.data.stickerIdCounter,
      isChooseEmoji: false
    })
    
    wx.showToast({
      title: i18n.t('modify.emojiAdded'),
      icon: 'success',
      duration: 1000
    })
  },

  // 从相册选择自定义图片
  chooseCustomImage(){
    var self = this
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album'],
      success: function (res) {
        var tempFilePath = res.tempFilePaths[0]
        self.addImageSticker(tempFilePath)
      },
      fail: function (res) {
        wx.showToast({
          title: i18n.t('modify.chooseImageFailed'),
          icon: 'none'
        })
      }
    })
  },

  // 拍照添加贴图
  takePhoto(){
    var self = this
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['camera'],
      success: function (res) {
        var tempFilePath = res.tempFilePaths[0]
        self.addImageSticker(tempFilePath)
      },
      fail: function (res) {
        wx.showToast({
          title: i18n.t('modify.takePhotoFailed'),
          icon: 'none'
        })
      }
    })
  },

  // 添加图片贴图
  addImageSticker(imagePath){
    // 使用固定的逻辑像素大小，不依赖设备比例
    var sticker = {
      id: ++this.data.stickerIdCounter,
      type: 'image',
      src: imagePath,
      x: 100,
      y: 100,
      width: 120,
      height: 120,
      zIndex: this.data.stickerIdCounter,
      isActive: false,
      scale: 1,
      rotation: 0
    }
    
    var stickers = this.data.stickers
    stickers.push(sticker)
    
    this.setData({
      stickers: stickers,
      stickerIdCounter: this.data.stickerIdCounter,
      isChooseCustomImage: false
    })
    
    wx.showToast({
      title: i18n.t('modify.imageAdded'),
      icon: 'success',
      duration: 1000
    })
  },

  // 选择贴图
  selectSticker(e){
    var stickerId = e.currentTarget.dataset.id
    var stickers = this.data.stickers
    
    // 取消所有贴图的激活状态
    stickers.forEach(function(sticker) {
      sticker.isActive = false
    })
    
    // 激活当前点击的贴图
    var targetSticker = stickers.find(function(sticker) {
      return sticker.id == stickerId
    })
    
    if (targetSticker) {
      targetSticker.isActive = true
      // 提升层级
      targetSticker.zIndex = ++this.data.stickerIdCounter
    }
    
    this.setData({
      stickers: stickers,
      activeStickerId: stickerId,
      stickerIdCounter: this.data.stickerIdCounter
    })
  },

  // 贴图移动开始
  stickerMoveStart(e){
    var stickerId = e.currentTarget.dataset.id
    this.stickerStartX = e.touches[0].clientX
    this.stickerStartY = e.touches[0].clientY
    this.movingStickerId = stickerId
    
    // 先选择这个贴图
    this.selectSticker(e)
  },

  // 贴图移动
  stickerMove(e){
    if (!this.movingStickerId) return
    
    var dragLengthX = e.touches[0].clientX - this.stickerStartX
    var dragLengthY = e.touches[0].clientY - this.stickerStartY
    
    var stickers = this.data.stickers
    var targetSticker = stickers.find(sticker => sticker.id == this.movingStickerId)
    
    if (targetSticker) {
      var newX = targetSticker.x + dragLengthX
      var newY = targetSticker.y + dragLengthY
      
      // 限制移动范围
      var maxX = 750 * this.deviceRatio - targetSticker.width
      var maxY = this.imgViewHeight - targetSticker.height
      
      if (newX < 0) newX = 0
      if (newX > maxX) newX = maxX
      if (newY < 0) newY = 0
      if (newY > maxY) newY = maxY
      
      targetSticker.x = newX
      targetSticker.y = newY
      
      this.setData({
        stickers: stickers
      })
    }
    
    this.stickerStartX = e.touches[0].clientX
    this.stickerStartY = e.touches[0].clientY
  },

  // 贴图移动结束
  stickerMoveEnd(e){
    this.movingStickerId = null
  },

  // 贴图缩放开始
  stickerResizeStart(e){
    if (e.stopPropagation) e.stopPropagation() // 阻止事件冒泡，避免触发移动
    var stickerId = e.currentTarget.dataset.id
    this.resizingStickerId = stickerId
    
    // 获取当前贴图信息和中心点
    var stickers = this.data.stickers
    var targetSticker = stickers.find(sticker => sticker.id == stickerId)
    if (targetSticker) {
      this.resizeStartScale = targetSticker.scale
      this.resizeCenterX = targetSticker.x + targetSticker.width / 2
      this.resizeCenterY = targetSticker.y + targetSticker.height / 2
      
      // 计算初始距离（从贴图中心到触摸点）
      this.resizeStartDistance = Math.sqrt(
        Math.pow(e.touches[0].clientX - this.resizeCenterX, 2) + 
        Math.pow(e.touches[0].clientY - this.resizeCenterY, 2)
      )
    }
  },

  // 贴图缩放
  stickerResize(e){
    if (e.stopPropagation) e.stopPropagation()
    if (!this.resizingStickerId) return
    
    // 计算当前距离（从贴图中心到当前触摸点）
    var currentDistance = Math.sqrt(
      Math.pow(e.touches[0].clientX - this.resizeCenterX, 2) + 
      Math.pow(e.touches[0].clientY - this.resizeCenterY, 2)
    )
    
    // 计算缩放比例
    var scaleRatio = currentDistance / this.resizeStartDistance
    var newScale = this.resizeStartScale * scaleRatio
    
    // 限制缩放范围
    if (newScale < 0.3) newScale = 0.3
    if (newScale > 3) newScale = 3
    
    var stickers = this.data.stickers
    var targetSticker = stickers.find(sticker => sticker.id == this.resizingStickerId)
    
    if (targetSticker) {
      targetSticker.scale = newScale
      
      this.setData({
        stickers: stickers
      })
    }
  },

  // 贴图缩放结束
  stickerResizeEnd(e){
    if (e.stopPropagation) e.stopPropagation()
    this.resizingStickerId = null
  },

  // 贴图旋转开始
  stickerRotateStart(e){
    if (e.stopPropagation) e.stopPropagation()
    var stickerId = e.currentTarget.dataset.id
    this.rotatingStickerId = stickerId
    
    // 获取贴图中心点
    var stickers = this.data.stickers
    var targetSticker = stickers.find(sticker => sticker.id == stickerId)
    if (targetSticker) {
      this.rotateCenterX = targetSticker.x + targetSticker.width / 2
      this.rotateCenterY = targetSticker.y + targetSticker.height / 2
      this.rotateStartAngle = this.getAngle(e.touches[0].clientX, e.touches[0].clientY, this.rotateCenterX, this.rotateCenterY)
      this.rotateStartRotation = targetSticker.rotation
    }
  },

  // 贴图旋转
  stickerRotate(e){
    if (e.stopPropagation) e.stopPropagation()
    if (!this.rotatingStickerId) return
    
    var currentAngle = this.getAngle(e.touches[0].clientX, e.touches[0].clientY, this.rotateCenterX, this.rotateCenterY)
    var deltaAngle = currentAngle - this.rotateStartAngle
    var newRotation = this.rotateStartRotation + deltaAngle
    
    // 标准化角度到 0-360 度
    while (newRotation < 0) newRotation += 360
    while (newRotation >= 360) newRotation -= 360
    
    var stickers = this.data.stickers
    var targetSticker = stickers.find(sticker => sticker.id == this.rotatingStickerId)
    
    if (targetSticker) {
      targetSticker.rotation = newRotation
      
      this.setData({
        stickers: stickers
      })
    }
  },

  // 贴图旋转结束
  stickerRotateEnd(e){
    if (e.stopPropagation) e.stopPropagation()
    this.rotatingStickerId = null
  },

  // 计算角度（弧度转角度）
  getAngle(x1, y1, x2, y2) {
    var deltaX = x1 - x2
    var deltaY = y1 - y2
    var angle = Math.atan2(deltaY, deltaX) * (180 / Math.PI)
    return angle
  },

  // 删除贴图
  deleteSticker(e){
    var stickerId = e.currentTarget.dataset.id
    var stickers = this.data.stickers.filter(function(sticker) {
      return sticker.id != stickerId
    })
    
    this.setData({
      stickers: stickers,
      activeStickerId: null
    })
    
    wx.showToast({
      title: i18n.t('modify.stickerDeleted'),
      icon: 'success',
      duration: 1000
    })
  },

  // 删除所有贴图
  deleteAllStickers(){
    var self = this
    wx.showModal({
      title: i18n.t('modify.confirmDeleteTitle'),
      content: i18n.t('modify.confirmDeleteAll'),
      success: function(res) {
        if (res.confirm) {
          self.setData({
            stickers: [],
            activeStickerId: null,
            stickerIdCounter: 0
          })
          wx.showToast({
            title: i18n.t('modify.stickersCleared'),
            icon: 'success',
            duration: 1000
          })
        }
      }
    })
  },
  //保存照片
  saveImgToPhone(){
    var self = this
    
    // 如果是表盘模式，跳转到裁剪页面
    if (self.data.fromDial) {
      console.log('表盘模式保存，当前图片路径:', self.data.tempImageSrc)
      
      // 如果有贴图，先保存合成图片再跳转
      if (self.data.stickers && self.data.stickers.length > 0) {
        console.log('有贴图，先合成图片')
        saveStickerImageOnly(self, function() {
          console.log('贴图合成完成，跳转到裁剪页面，图片路径:', self.data.tempImageSrc)
          // 合成完成后跳转到裁剪页面
          wx.navigateTo({
            url: '/pages/function_test/dial_operate/dial_add_background/dial_cut_image/index?imagePath=' + encodeURIComponent(self.data.tempImageSrc) + '&width=' + self.data.devScreenWidth + '&height=' + self.data.devScreenHeight,
            events: {
              onDialBgData: (resDialBg) => {
                console.log('收到裁剪页面返回数据:', resDialBg)
                // 从dial_cut_image返回时的回调，传递给dial_add_background
                const pages = getCurrentPages()
                const dialAddBgPage = pages.find(page => page.route.includes('dial_add_background'))
                if (dialAddBgPage && dialAddBgPage._handleDialBgData) {
                  dialAddBgPage._handleDialBgData(resDialBg.data)
                }
                // 关闭当前页面返回到dial_add_background
                wx.navigateBack()
              }
            }
          })
        })
      } else {
        console.log('无贴图，直接跳转到裁剪页面，图片路径:', self.data.tempImageSrc)
        // 没有贴图，直接跳转到裁剪页面
        wx.navigateTo({
          url: '/pages/function_test/dial_operate/dial_add_background/dial_cut_image/index?imagePath=' + encodeURIComponent(self.data.tempImageSrc) + '&width=' + self.data.devScreenWidth + '&height=' + self.data.devScreenHeight,
          events: {
            onDialBgData: (resDialBg) => {
              console.log('收到裁剪页面返回数据:', resDialBg)
              // 直接跳转到dial_add_background页面
              wx.redirectTo({
                url: '/pages/function_test/dial_operate/dial_add_background/index?fromCut=true',
                success: () => {
                  // 通过全局变量传递数据
                  getApp().globalData = getApp().globalData || {}
                  getApp().globalData.dialBgData = resDialBg.data
                }
              })
            }
          }
        })
      }
      return
    }
    
    // 普通模式：保存到相册
    // 如果有贴图，先保存合成图片
    if (self.data.stickers && self.data.stickers.length > 0) {
      saveStickerImageOnly(self)
      // 延迟一下再保存到相册
      setTimeout(function() {
        self.saveToAlbum()
      }, 500)
    } else {
      // 没有贴图，直接保存
      self.saveToAlbum()
    }
  },
  
  // 保存到相册
  saveToAlbum(){
    var self = this
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              self.doSaveToAlbum()
            },
            fail() {
              wx.showModal({
                title: i18n.t('modify.authTitle'),
                content: i18n.t('modify.authContent'),
                showCancel: false,
                confirmText: i18n.t('common.ok'),
                confirmColor: '#ff69b4'
              })
            }
          })
        } else {
          self.doSaveToAlbum()
        }
      }
    })
  },
  
  // 执行保存到相册
  doSaveToAlbum(){
    var self = this
    wx.showLoading({
      title: i18n.t('modify.saving'),
      mask: true
    })
    
    wx.saveImageToPhotosAlbum({
      filePath: self.data.tempImageSrc,
      success: function() {
        wx.hideLoading()
        wx.showToast({
          title: i18n.t('modify.saveSuccess'),
          icon: 'success',
          duration: 2000
        })
      },
      fail: function(err) {
        wx.hideLoading()
        console.error('保存失败:', err)
        wx.showModal({
          title: i18n.t('modify.saveFailedTitle'),
          content: i18n.t('modify.saveFailedContent'),
          showCancel: false,
          confirmText: i18n.t('common.ok'),
          confirmColor: '#ff69b4'
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
    onShow: function () {
    this.updateTexts()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
// 多语言：更新界面文案
function buildL10n() {
  return {
    title: i18n.t('modify.title'),
    welcomeTitle: i18n.t('modify.welcomeTitle'),
    welcomeSubtitle: i18n.t('modify.welcomeSubtitle'),
    welcomeTip: i18n.t('modify.welcomeTip'),
    toolbarCrop: i18n.t('modify.toolbarCrop'),
    toolbarText: i18n.t('modify.toolbarText'),
    toolbarDoodle: i18n.t('modify.toolbarDoodle'),
    toolbarSticker: i18n.t('modify.toolbarSticker'),
    cropToolbarBack: i18n.t('modify.cropToolbarBack'),
    cropToolbarOpenBox: i18n.t('modify.cropToolbarOpenBox'),
    cropToolbarBestShow: i18n.t('modify.cropToolbarBestShow'),
    doodleTopChooseColor: i18n.t('modify.doodleTopChooseColor'),
    quickBrushTitle: i18n.t('modify.quickBrushTitle'),
    presetThin: i18n.t('modify.presetThin'),
    presetMedium: i18n.t('modify.presetMedium'),
    presetThick: i18n.t('modify.presetThick'),
    presetMarker: i18n.t('modify.presetMarker'),
    doodleBack: i18n.t('modify.doodleBack'),
    doodleQuickBrush: i18n.t('modify.doodleQuickBrush'),
    doodleColor: i18n.t('modify.doodleColor'),
    doodleEraser: i18n.t('modify.doodleEraser'),
    doodleClear: i18n.t('modify.doodleClear'),
    stickerTopChooseEmoji: i18n.t('modify.stickerTopChooseEmoji'),
    stickerTopChooseImage: i18n.t('modify.stickerTopChooseImage'),
    stickerFromAlbum: i18n.t('modify.stickerFromAlbum'),
    stickerTakePhoto: i18n.t('modify.stickerTakePhoto'),
    stickerBack: i18n.t('modify.stickerBack'),
    stickerSave: i18n.t('modify.stickerSave'),
    stickerEmoji: i18n.t('modify.stickerEmoji'),
    stickerImage: i18n.t('modify.stickerImage'),
    stickerClearAll: i18n.t('modify.stickerClearAll'),
    textTopChooseSize: i18n.t('modify.textTopChooseSize'),
    textSizeMin: i18n.t('modify.textSizeMin'),
    textSizeMax: i18n.t('modify.textSizeMax'),
    textTopChooseColor: i18n.t('modify.textTopChooseColor'),
    textItalic: i18n.t('modify.textItalic'),
    textBold: i18n.t('modify.textBold'),
    textBack: i18n.t('modify.textBack'),
    textAdd: i18n.t('modify.textAdd'),
    textSize: i18n.t('modify.textSize'),
    textColor: i18n.t('modify.textColor'),
    textStyle: i18n.t('modify.textStyle'),
  }
}

function chooseImage(self){
  wx.chooseImage({
    count: 1,
    // sizeType: ['original '], // 可以指定是原图还是压缩图，默认二者都有
    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
    success: function (res) {
      var tempFilePaths = res.tempFilePaths
      self.setData({
        imageNotChoosed: false,
        tempImageSrc: tempFilePaths[0],
        originImageSrc: tempFilePaths[0],
      })
      loadImgOnImage(self)
    },
    fail: function (res) {
      self.setData({
        imageNotChoosed: true
      })
    }
  })
}
function loadImgOnImage(self){
  wx.getImageInfo({
    src: self.data.tempImageSrc,
    success: function (res) {
      self.oldScale = 1
      self.initRatio = res.height / self.imgViewHeight  //转换为了px 图片原始大小/显示大小
      if (self.initRatio < res.width / (750 * self.deviceRatio)) {
        self.initRatio = res.width / (750 * self.deviceRatio)
      }
      //图片显示大小
      self.scaleWidth = (res.width / self.initRatio)
      self.scaleHeight = (res.height / self.initRatio)

      self.initScaleWidth = self.scaleWidth
      self.initScaleHeight = self.scaleHeight
      self.startX = 750 * self.deviceRatio / 2 - self.scaleWidth / 2;
      self.startY = self.imgViewHeight / 2 - self.scaleHeight / 2;
      self.setData({
        imgWidth: self.scaleWidth,
        imgHeight: self.scaleHeight,
        imgTop: self.startY,
        imgLeft: self.startX
      })
      wx.hideLoading();
    }
  })
}
function loadImgOnCanvas(self){
  wx.getImageInfo({
    src: self.data.tempImageSrc,
    success: function (res) {
      self.initRatio = res.height / self.imgViewHeight  //转换为了px 图片原始大小/显示大小
      if (self.initRatio < res.width / (750 * self.deviceRatio)) {
        self.initRatio = res.width / (750 * self.deviceRatio)
      }
      //图片显示大小
      self.scaleWidth = (res.width / self.initRatio)
      self.scaleHeight = (res.height / self.initRatio)

      self.initScaleWidth = self.scaleWidth
      self.initScaleHeight = self.scaleHeight
      self.startX = -self.scaleWidth / 2;
      self.startY = -self.scaleHeight / 2;
      self.ctx = wx.createCanvasContext('myCanvas')
      self.ctx.translate((750 * self.deviceRatio) / 2, self.imgViewHeight/ 2) //原点移至中心，保证图片居中显示
      self.ctx.drawImage(self.data.tempImageSrc, self.startX, self.startY, self.scaleWidth, self.scaleHeight)
      self.ctx.draw()
    }
  })
}

function throttle(fn, miniTimeCell) {
  var timer = null,
    previous = null;

  return function () {
    var now = +new Date(),
      context = this,
      args = arguments;
    if (!previous) previous = now;
    var remaining = now - previous;
    if (miniTimeCell && remaining >= miniTimeCell) {
      fn.apply(context, args);
      previous = now;
    }
  }
}
const fn = throttle(drawOnTouchMove, 100)

function drawOnTouchMove(self, e) {
  let { minScale, maxScale } = self.data
  let [touch0, touch1] = e.touches
  let xMove, yMove, newDistance, xDistance, yDistance

  if (e.timeStamp - self.timeOneFinger < 100) {//touch时长过短，忽略
    return
  }

  // 单指手势时触发
  if (e.touches.length === 1) {
    //计算单指移动的距离
    xMove = touch0.clientX - self.touchX
    yMove = touch0.clientY - self.touchY
    //转换移动距离到正确的坐标系下
    self.imgLeft = self.startX + xMove
    self.imgTop = self.startY + yMove

    self.setData({
      imgTop: self.imgTop,
      imgLeft: self.imgLeft
    })
  }
  // 两指手势触发
  if (e.touches.length >= 2) {
    // self.timeMoveTwo = e.timeStamp
    // 计算二指最新距离
    xDistance = touch1.clientX - touch0.clientX
    yDistance = touch1.clientY - touch0.clientY
    newDistance = Math.sqrt(xDistance * xDistance + yDistance * yDistance)

    //  使用0.005的缩放倍数具有良好的缩放体验
    self.newScale = self.oldScale + 0.005 * (newDistance - self.oldDistance)

    //  设定缩放范围
    self.newScale <= minScale && (self.newScale = minScale)
    self.newScale >= maxScale && (self.newScale = maxScale)

    self.scaleWidth = self.newScale * self.initScaleWidth
    self.scaleHeight = self.newScale * self.initScaleHeight

    self.imgLeft = self.deviceRatio*750 / 2 - self.newScale * self.initLeft
    self.imgTop = self.imgViewHeight / 2 - self.newScale *self.initTop
    self.setData({
      imgTop: self.imgTop,
      imgLeft: self.imgLeft,
      imgWidth: self.scaleWidth,
      imgHeight: self.scaleHeight
    })

  }
}

function saveImgUseTempCanvas(self, delay, fn){
  setTimeout(function () {
    wx.canvasToTempFilePath({
      x:0,
      y:0,
      width: self.data.tempCanvasWidth,
      height: self.data.tempCanvasHeight,
      destWidth: self.data.tempCanvasWidth,
      destHeight: self.data.tempCanvasHeight,
      fileType: 'png',
      quality: 1,
      canvasId: 'tempCanvas',
      success: function (res) {
        wx.hideLoading();
        console.log(res.tempFilePath)
        self.setData({
          tempImageSrc: res.tempFilePath
        })
        if(fn){
          fn(self) 
        }
      }
    })
  }, delay)
}
function saveDoodle(self,fn) {
    wx.canvasToTempFilePath({
      x: (750 * self.deviceRatio) / 2 + self.startX,
      y: self.imgViewHeight / 2 + self.startY,
      width: self.scaleWidth,
      height: self.scaleHeight,
      canvasId: 'myCanvas',
      success: function (res) {
        if(self.cleared){
          self.cleared=false
          self.setData({
            doodleImageSrc: res.tempFilePath,
            tempCanvasWidth: self.scaleWidth,
            tempCanvasHeight: self.scaleHeight
          })
          var ctx = wx.createCanvasContext('tempCanvas')
          ctx.drawImage(self.data.tempImageSrc, 0, 0, self.scaleWidth,self.scaleHeight)
          ctx.drawImage(self.data.doodleImageSrc, 0, 0, self.scaleWidth, self.scaleHeight)
          ctx.draw()
          saveImgUseTempCanvas(self, 100, fn)
        }else{
          self.setData({
            tempImageSrc: res.tempFilePath,
            originImageSrc: res.tempFilePath
          })
          fn(self)
        }
      }
    })
}

// 保存贴图合成图片
function saveStickerImage(self, fn) {
  wx.showLoading({
    title: i18n.t('modify.savingStickers'),
    mask: true,
  })
  
  // 使用原始图片尺寸，确保保存质量
  var canvasWidth = self.scaleWidth * self.initRatio
  var canvasHeight = self.scaleHeight * self.initRatio
  
  self.setData({
    tempCanvasWidth: canvasWidth,
    tempCanvasHeight: canvasHeight
  })
  
  var ctx = wx.createCanvasContext('tempCanvas')
  // 绘制底图
  ctx.drawImage(self.data.tempImageSrc, 0, 0, canvasWidth, canvasHeight)
  
  // 绘制所有贴图
  var stickers = self.data.stickers
  for (var i = 0; i < stickers.length; i++) {
    var sticker = stickers[i]
    
    // 使用initRatio确保在保存时贴图尺寸正确
    var stickerX = (sticker.x - self.startX) * self.initRatio
    var stickerY = (sticker.y - self.startY) * self.initRatio
    var stickerW = sticker.width * self.initRatio
    var stickerH = sticker.height * self.initRatio
    
    // 计算贴图中心点
    var centerX = stickerX + stickerW / 2
    var centerY = stickerY + stickerH / 2
    
    // 保存canvas状态
    ctx.save()
    
    // 移动到贴图中心
    ctx.translate(centerX, centerY)
    
    // 应用缩放
    var finalScale = sticker.scale || 1
    ctx.scale(finalScale, finalScale)
    
    // 应用旋转
    if (sticker.rotation) {
      ctx.rotate(sticker.rotation * Math.PI / 180)
    }
    
    if (sticker.type === 'image') {
      ctx.drawImage(sticker.src, -stickerW / 2, -stickerH / 2, stickerW, stickerH)
    } else if (sticker.type === 'emoji') {
      ctx.setTextAlign('center')
      ctx.setTextBaseline('middle')
      ctx.setFillStyle('#000000')
      // 修复字体格式和大小计算
      var fontSize = Math.round((sticker.fontSize || 60) * self.initRatio)
      if (fontSize < 1) fontSize = 1
      ctx.font = 'normal normal ' + fontSize + 'px sans-serif'
      ctx.fillText(sticker.emoji, 0, 0)
    }
    
    // 恢复canvas状态
    ctx.restore()
  }
  
  ctx.draw()
  
  // 保存图片
  saveImgUseTempCanvas(self, 100, function() {
    // 清空贴图数组
    self.setData({
      stickers: [],
      activeStickerId: null,
      stickerIdCounter: 0
    })
    if (fn) fn(self)
  })
}

// 检查并自动保存贴图（用于页面切换时）
function autoSaveStickerIfNeeded(self, callback) {
  if (self.data.page === 'stickerPage' && self.data.stickers.length > 0) {
    // 当前在贴图页面且有贴图，自动保存
    wx.showLoading({
      title: i18n.t('modify.autoSavingStickers'),
      mask: true,
    })
    
    // 使用原始图片尺寸，确保保存质量
    var canvasWidth = self.scaleWidth * self.initRatio
    var canvasHeight = self.scaleHeight * self.initRatio
    
    self.setData({
      tempCanvasWidth: canvasWidth,
      tempCanvasHeight: canvasHeight
    })
    
    var ctx = wx.createCanvasContext('tempCanvas')
    // 绘制底图
    ctx.drawImage(self.data.tempImageSrc, 0, 0, canvasWidth, canvasHeight)
    
    // 绘制所有贴图
    var stickers = self.data.stickers
    for (var i = 0; i < stickers.length; i++) {
      var sticker = stickers[i]
      
      // 使用initRatio确保在保存时贴图尺寸正确
      var stickerX = (sticker.x - self.startX) * self.initRatio
      var stickerY = (sticker.y - self.startY) * self.initRatio
      var stickerW = sticker.width * self.initRatio
      var stickerH = sticker.height * self.initRatio
      
      // 计算贴图中心点
      var centerX = stickerX + stickerW / 2
      var centerY = stickerY + stickerH / 2
      
      // 保存canvas状态
      ctx.save()
      
      // 移动到贴图中心
      ctx.translate(centerX, centerY)
      
      // 应用缩放
      var finalScale = sticker.scale || 1
      ctx.scale(finalScale, finalScale)
      
      // 应用旋转
      if (sticker.rotation) {
        ctx.rotate(sticker.rotation * Math.PI / 180)
      }
      
      if (sticker.type === 'image') {
        ctx.drawImage(sticker.src, -stickerW / 2, -stickerH / 2, stickerW, stickerH)
      } else if (sticker.type === 'emoji') {
        ctx.setTextAlign('center')
        ctx.setTextBaseline('middle')
        ctx.setFillStyle('#000000')
        // 修复字体格式和大小计算
        var fontSize = Math.round((sticker.fontSize || 60) * self.initRatio)
        if (fontSize < 1) fontSize = 1
        ctx.font = 'normal normal ' + fontSize + 'px sans-serif'
        ctx.fillText(sticker.emoji, 0, 0)
      }
      
      // 恢复canvas状态
      ctx.restore()
    }
    
    ctx.draw()
    
    // 保存图片并清空贴图状态
    saveImgUseTempCanvas(self, 100, function() {
      // 清空贴图状态
      self.setData({
        stickers: [],
        activeStickerId: null,
        stickerIdCounter: 0
      })
      loadImgOnImage(self)
      wx.hideLoading()
      if (callback) callback()
    })
  } else {
    // 不需要保存，直接执行回调
    if (callback) callback()
  }
}

// 仅保存贴图合成图片（不清空贴图）
function saveStickerImageOnly(self, callback) {
  wx.showLoading({
    title: i18n.t('modify.saving'),
    mask: true,
  })
  
  console.log('开始保存贴图合成，原始图片:', self.data.tempImageSrc)
  console.log('贴图数量:', self.data.stickers.length)
  
  // 获取原始图片信息来确定画布尺寸
  wx.getImageInfo({
    src: self.data.tempImageSrc,
    success: function (res) {
      console.log('原始图片信息:', res)
      
      // 使用原始图片尺寸，确保保存质量
      var canvasWidth = res.width
      var canvasHeight = res.height
      
      self.setData({
        tempCanvasWidth: canvasWidth,
        tempCanvasHeight: canvasHeight
      })
      
      console.log('设置画布尺寸:', canvasWidth, 'x', canvasHeight)
      
      var ctx = wx.createCanvasContext('tempCanvas')
      // 绘制底图
      ctx.drawImage(self.data.tempImageSrc, 0, 0, canvasWidth, canvasHeight)
      
      // 绘制所有贴图
      var stickers = self.data.stickers
      for (var i = 0; i < stickers.length; i++) {
        var sticker = stickers[i]
        console.log('绘制贴图:', sticker)
        
        // 计算贴图在原始图片中的位置和尺寸
        var scaleRatio = canvasWidth / self.scaleWidth
        var stickerX = (sticker.x - self.startX) * scaleRatio
        var stickerY = (sticker.y - self.startY) * scaleRatio
        var stickerW = sticker.width * scaleRatio
        var stickerH = sticker.height * scaleRatio
        
        // 计算贴图中心点
        var centerX = stickerX + stickerW / 2
        var centerY = stickerY + stickerH / 2
        
        // 保存canvas状态
        ctx.save()
        
        // 移动到贴图中心
        ctx.translate(centerX, centerY)
        
        // 应用缩放
        var finalScale = sticker.scale || 1
        ctx.scale(finalScale, finalScale)
        
        // 应用旋转
        if (sticker.rotation) {
          ctx.rotate(sticker.rotation * Math.PI / 180)
        }
        
        if (sticker.type === 'image') {
          ctx.drawImage(sticker.src, -stickerW / 2, -stickerH / 2, stickerW, stickerH)
        } else if (sticker.type === 'emoji') {
          ctx.setTextAlign('center')
          ctx.setTextBaseline('middle')
          ctx.setFillStyle('#000000')
          // 修复字体格式和大小计算
          var fontSize = Math.round((sticker.fontSize || 60) * scaleRatio)
          if (fontSize < 1) fontSize = 1
          ctx.font = 'normal normal ' + fontSize + 'px sans-serif'
          ctx.fillText(sticker.emoji, 0, 0)
        }
        
        // 恢复canvas状态
        ctx.restore()
      }
      
      ctx.draw()
      
      // 保存图片但不清空贴图
      saveImgUseTempCanvas(self, 100, function() {
        console.log('贴图合成完成，新图片路径:', self.data.tempImageSrc)
        wx.hideLoading()
        if (callback) callback()
      })
    },
    fail: function(err) {
      console.error('获取图片信息失败:', err)
      wx.hideLoading()
      if (callback) callback()
    }
  })
}